package cn.swu.lyx.homework4

import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.view.View
import android.widget.EditText
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import cn.swu.lyx.homework4.dao.UserDao


class register : AppCompatActivity() {
    var userAccount: EditText? = null
    var userPassword: EditText? = null
    var userName: EditText? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_register)
        userAccount=findViewById(R.id.ruserAccount)
        userPassword=findViewById(R.id.userPassword)
        userName=findViewById(R.id.userName)
    }
    fun register(view: View?) {
        val userAccount1 = userAccount?.text.toString()
        val userPassword1 = userPassword!!.text.toString()
        val userName1 = userName!!.text.toString()
        val user = User()
        user.userAccount = userAccount1
        user.userPassword = userPassword1
        user.userName = userName1
        user.userType = 1
        user.userState = 0
        user.userDel = 0
        object : Thread() {
            override fun run() {
                var msg = 0
                val userDao = UserDao()
                var uu = userDao.findUser(user.userAccount)
                if (uu != null) {
                    msg = 1
                    uu=null
                } else {
                    val flag = userDao.register(user)
                    if (flag) {
                        msg = 2
                    }
                }
                hand.sendEmptyMessage(msg)
            }
        }.start()
    }

    @SuppressLint("HandlerLeak")
    val hand: Handler = object : Handler() {
        override fun handleMessage(msg: Message) {
            if (msg.what == 0) {
                Toast.makeText(applicationContext, "注册失败", Toast.LENGTH_LONG).show()
            } else if (msg.what == 1) {
                Toast.makeText(applicationContext, "该账号已经存在，请换一个账号", Toast.LENGTH_LONG).show()
            } else if (msg.what == 2) {
                Toast.makeText(applicationContext, "注册成功", Toast.LENGTH_LONG).show()
                val intent = Intent()
                //将想要传递的数据用putExtra封装在intent中
                intent.putExtra("a", "注册")
                setResult(RESULT_CANCELED, intent)
                finish()
            }
        }
    }
    companion object {
        private const val TAG = "mysql-register"
    }
}
